/**
 * @file 角色详情
 * @date 2025/11/08 23:40:23
 * @author lyqjob@yeah.net
 */

/* global process */

import {  useState, useEffect, useMemo , useRef, useCallback } from 'react';
import { Form, Input, Button, Descriptions, Flex, Select, Switch, Tabs , message } from 'antd';
import { Link ,useNavigate, useSearchParams } from 'react-router-dom';
import { LeftOutlined ,RightOutlined } from '@ant-design/icons';
import AuthButton from '@/components/AuthButton';
import FunctionPermission from '../components/FunctionPermission.jsx';
import DataPermission from '../components/DataPermission.jsx';
// import AdvancedDataPermission from '../components/AdvancedDataPermission.jsx';
import { adminApi } from '@/services/admin.js';
import Audit from '@/components/Audit/index.jsx';
import styles from './index.less';


// 角色类型
const roleTypes = {
    'system': '系统内置',
    'custom': '自定义',
    'special': '特殊角色',
}
  

// 权限层级
const roleLevels = {
  0: '访客', 
  10: '普通用户', 
  20: '部门管理员', 
  30: '业务管理员', 
  40: '系统管理员', 
  99: '超级管理员'
};

const RoleDetail = () => {
    const [searchParams] = useSearchParams();
    const id = searchParams.get('id');
    const access_type = searchParams.get('type');// 访问类型：add/edit/view
    const navigate = useNavigate();
    const referrer =  '/setting/role';
    const functionPermissionRef = useRef(null);
    const dataPermissionRef = useRef(null);
    const [is_edit, setIsedit] = useState(false);
    const [form] = Form.useForm();
    const [formData, setFormData] = useState({});//表单数据
    const [departmentList, setDepartmentList] = useState([]);//部门列表
    const [roleList, setRoleList] = useState([]);//角色列表
    const [currentIndex, setCurrentIndex] = useState(-1);//当前选中项
    const [navigationLoading, setNavigationLoading] = useState(false);
    const [checkedKeys, setCheckedKeys] = useState([]);// 功能权限菜单选中
    const [permissionData, setPermissionData] = useState([]);//权限树数据
    const [rolePermissions, setRolePermissions] = useState([]);//角色已绑定的权限列表
    const [menuSource, setMenuSource] = useState([]);//菜单数据



    // 子组件触发父组件变化
    const onParentChange = useCallback((type, value) => {
        if (type === 'function') {
            setCheckedKeys(value);
        }
    }, []);

    // 处理编辑按钮点击
    const handleEditClick = () => {
        setIsedit(true);
    }

    // 处理取消按钮点击
    const handleCancelClick = () => {
        setIsedit(false);
        form.resetFields();
    }

    // 处理保存按钮点击
    const handleSaveClick = () => {
        form.submit();
    }
    

    useEffect(() => {
        if(access_type === 'add'){
            setIsedit(true)
            // 新增角色默认赋值
            form.setFieldsValue({status:true,permission_level:0,role_type:'custom'});
        }
        if (access_type === 'edit' || access_type === 'view') {
            setIsedit(access_type === 'edit')
            getRoleInfo(id)
            getRoleList()
            getRolePermissions(id)
            getRoleBindMenus(id)

        }
        
    }, [id, access_type]); // 移除函数依赖项，避免无限循环

    useEffect(() => {
        if (formData && Object.keys(formData).length > 0) {
            form.setFieldsValue({...formData,status:formData.status===0?true:false});
            setNavigationLoading(false)
            return
        }

    }, [formData]); // 移除 form 依赖项


    useEffect(() => {
        getPageData()
    }, []);

    const hasLoggedRef = useRef(false);
    useEffect(() => {
        if (process.env.NODE_ENV === 'development' && !hasLoggedRef.current) {
            // 父组件渲染
            hasLoggedRef.current = true;
        }
    }, []);



    // Tree数据转换 - 根据 is_edit 状态优化展示
    const convertTreeData = useCallback((menus, currentCheckedKeys = [], editMode = false) => {
        if (!menus || menus.length === 0) {
            return [];
        }

        const convertNode = (item) => {
            console.log('item', item);
            console.log('currentCheckedKeys', currentCheckedKeys);
            const isChecked = currentCheckedKeys.includes(item.id);
            // 开发类型和目录类型不能授权
            const isDisabled = item.access_type === 0 || item.node_type === 1;
            
            return {
                title: editMode?item.name:(
                <>
                    {item.name} {item.access_type === 0 && '（开放）'}
                    {!editMode && isChecked && (
                        <span style={{ color: '#1890ff', fontSize: '12px', marginLeft: '4px' }}>
                            ✓ 已授权
                        </span>
                    )}
                </>
                ),
                key: item.id,
                disabled: isDisabled,
                children: item.children ? item.children.map(convertNode) : []
            };
        };

        return menus.map(convertNode);
    }, []);


    const computedTreeData = useMemo(() => {
        return convertTreeData(menuSource, checkedKeys, is_edit);
    }, [menuSource, checkedKeys, convertTreeData, is_edit]);

    // tab 项 - 使用 useMemo 缓存，优化依赖项（依赖 computedTreeData，确保子组件拿到最新树）
    const Items = useMemo(() => [
        {
            key: '1',
            label: '功能权限',
            children: <FunctionPermission ref={functionPermissionRef} checkedKeys={checkedKeys} onChange={onParentChange} treeData={computedTreeData} access_type={access_type} roleId={id} is_edit={is_edit} permissionData={permissionData} rolePermissions={rolePermissions} />,
        },
        {
            key: '2',
            label: '数据权限',
            children: <DataPermission ref={dataPermissionRef} access_type={access_type} is_edit={is_edit} scope={formData.data_scope} curstom_ids={formData?.data_scope_dept_ids||[]}/>
        },
        // {
        //     key: '3',
        //     label: '更精细的数据权限',
        //     children: <AdvancedDataPermission />
        // }
    ], [checkedKeys, onParentChange, computedTreeData, access_type, id, is_edit, permissionData, formData.data_scope, formData.data_scope_dept_ids]);


    // 获取权限数据
    const getPermissionTree = useCallback(async () => {
        const [err, res] = await adminApi.getPermissions({ page: 1, limit: 1000 });
        if (err) {
            // 获取权限数据失败
            return { data: { data: [] } };
        }
        return res;
    }, []);

    // 获取部门列表
    const getDepartmentList = useCallback(async () => {
        const [err, res] = await adminApi.getAllDepartment({ current: 1, pageSize: 1000 });
        if (err) {
            // 获取部门列表失败
            return { data: { data: [] } };
        }
        return res;
    }, []);

    // 获取菜单树
    const getMenuTree = useCallback(async () => {
        const [err, res] = await adminApi.getMenuTree({ page: 1, limit: 1000 });
        if (err) {
            // 获取菜单树失败
            return { data: { data: [] } };
        }
        return res;
    }, []);

    // 获取页面数据 - 优化版本
    const getPageData = useCallback(async () => {
        const [permissionRes, departmentRes, menuRes] = await Promise.all([
            getPermissionTree(),
            getDepartmentList(), 
            getMenuTree()
        ]);
        // 批量更新状态
        const permissionData = permissionRes?.data?.data || [];
        const departmentData = departmentRes?.data?.data || [];
        const menuData = menuRes?.data || [];

        setPermissionData(permissionData);
        setDepartmentList(departmentData);
        setMenuSource(menuData);
    }, []);

    // 获取角色列表（用于上一条/下一条导航）
    const getRoleList = useCallback(async () => {
        const [err, res] = await adminApi.getAllrole({ page: 1, limit: 1000 });
        if (err) {
            // 获取角色列表失败
            return;
        }
        if (res.code === 200 && res?.data?.data) {
            const roles = res.data.data;
            setRoleList(roles);
            
            // 找到当前角色在列表中的索引
            const currentIdx = roles.findIndex(role => role.id === parseInt(id));
            setCurrentIndex(currentIdx);
        }
    }, [id]);

    // 获取角色详情
    const getRoleInfo = useCallback(async (id) => {
        const [err, res] = await adminApi.getRoleInfo(id);
        if (err) {
            return;
        }
        setFormData(res.data);
    }, []);


    // 获取角色已绑定菜单
    const getRoleBindMenus = useCallback(async (roleId) => {
        const [err, res] = await adminApi.getRoleBindMenus(roleId);
        if (err) {
            // setLoading(false);
            return;
        }
        if (res.code === 200 && res.data) {
            const bindids = res.data.map(item => item.id);
            setCheckedKeys(bindids)
        }
        
    }, []);

    // 获取角色已绑定的权限列表
    const getRolePermissions = useCallback(async (roleId) => {
        // setLoading(true);
        const [err, res] = await adminApi.getRolePermissions(roleId);
        if (err) {
            // setLoading(false);
            return;
        }
        setRolePermissions(res.data || []);
        // setLoading(false);
    }, []);

    // 导航到上一个角色
    const navigateToPrevious = () => {
        if (currentIndex > 0 && !navigationLoading) {
             // 清除选中
            setCheckedKeys([]);
            setRolePermissions([]);
            setNavigationLoading(true);
            const previousRole = roleList[currentIndex - 1];
            navigate(`/setting/role/info?type=view&id=${previousRole.id}`, { 
                state: { from: referrer },
                replace: false 
            });
        }
    }

    // 导航到下一个角色
    const navigateToNext = () => {
        if (currentIndex < roleList.length - 1 && !navigationLoading) {
            // 清除选中
            setCheckedKeys([]);
            setRolePermissions([]);

            setNavigationLoading(true);
            const nextRole = roleList[currentIndex + 1];
            navigate(`/setting/role/info?type=view&id=${nextRole.id}`, { 
                state: { from: referrer },
                replace: false 
            });
        }
    }

    // 部门选项
    const departmentOptionsMemo = useMemo(() => {
        return departmentList.map(item => (
            <Select.Option
            key={item.id}
            disabled={item.is_protected === 1}
            value={item.id}
            >
            {item.name}
            </Select.Option>
        ));
    }, [departmentList]);

    // 切换tab
    // const handleTabChange = (key) => {
    //     setTabKey(key);
    // }

    // Descript列配置
    const cloumns = useMemo(() => {
        if (!formData) {
            return [];
        }

        return [
            {
                key: 'code',
                label: !is_edit ? '角色编码' : '',
                children: is_edit ? (
                    <Form.Item
                        label={is_edit ? '角色编码' : ''}
                        name="code"
                        rules={[{ required: access_type !== 'add', message: '请添加角色编码' }]}
                        style={{ marginBottom: 0 ,width: '100%'}}
                    >
                        <Input disabled placeholder='自动生成' />
                    </Form.Item>
                ) : (formData.code || '-'),
            },
            {
                key: 'name',
                label: !is_edit ? '角色名称' : '',
                children: is_edit ? (
                    <Form.Item
                        label={is_edit ? '角色名称' : ''}
                        name="name"
                        rules={[{ required: true, message: '请添加角色名称' }]}
                        style={{ marginBottom: 0 ,width: '100%'}}
                    >
                        <Input placeholder="请输入角色名称" />
                    </Form.Item>
                ) : (formData.name || '-'),
            },
            {
                key: 'dept_id',
                label: !is_edit ? '组织/部门' : '',
                // span: 2,
                children: is_edit ? (
                    <Form.Item
                        label={is_edit ? '组织/部门' : ''}
                        name="dept_id"

                        wrapperCol={{ span: 18 }}
                        rules={[{ required: true, message: '请选择部门' }]}
                        style={{ marginBottom: 0 ,width: '100%'}}
                    >
                        <Select placeholder="请选择部门">
                            {departmentOptionsMemo}
                        </Select>
                    </Form.Item>
                ) : (formData.department_name || '-'),
            },
            {
                key: 'role_type',
                label: !is_edit ? '角色类型' : '',
                children: is_edit ? (
                    <Form.Item
                        label={is_edit ? '角色类型' : ''}
                        name="role_type"
                        rules={[{ required: true, message: '请选择角色类型' }]}
                        style={{ marginBottom: 0 ,width: '100%'}}
                    >
                        <Select placeholder="请选择角色类型">
                            {access_type && access_type!== 'add' && (<Select.Option key={'system'} value={'system'} disabled>系统内置</Select.Option>)}
                            <Select.Option key={'custom'} value={'custom'}>自定义</Select.Option>
                            <Select.Option key={'special'} value={'special'}>特殊角色</Select.Option>
                        </Select>
                    </Form.Item>
                ) : (roleTypes[formData.role_type] || '-'),
            },
            {
                key: 'permission_level',
                label: !is_edit ? '权限层级' : '',
                // span: 2,
                children: is_edit ? (
                    <Form.Item
                        label={is_edit ? '权限层级' : ''}
                        name="permission_level"
                        rules={[{ required: true, message: '请选择权限层级' }]}
                        style={{ marginBottom: 0 ,width: '100%'}}
                    >
                        <Select placeholder="请选择权限层级">
                            <Select.Option key={0} value={0}>访客</Select.Option>
                            <Select.Option key={10} value={10}>普通用户</Select.Option>
                            <Select.Option key={20} value={20}>部门管理员</Select.Option>
                            <Select.Option key={30} value={30}>业务管理员</Select.Option>
                            <Select.Option key={40} value={40}>系统管理员</Select.Option>
                            {
                                formData.permission_level === 99 && (
                                    <Select.Option disabled key={99} value={99}>超级管理员</Select.Option>
                                )
                            }
                        </Select>
                    </Form.Item>
                ) : (roleLevels[formData.permission_level] || '-'),
            },
            {
                key: 'status',
                label: !is_edit ? '状态' : '',
                children: is_edit ? (
                    <Form.Item
                        label={is_edit ? '状态' : ''}
                        name="status"
                        rules={[{ required: true, message: '请选择状态' }]}
                        valuePropName="checked"
                        style={{ marginBottom: 0 ,width: '100%'}}
                    >
                        <Switch checkedChildren="正常" unCheckedChildren="停用" />
                    </Form.Item>
                ) : (formData.status === 0 ? '启用' : '停用'),
            },
            {
                key: 'description',
                label: !is_edit ? '描述' : '',
                span: 2,
                children: is_edit ? (
                    <Form.Item
                        label={is_edit ? '描述' : ''}
                        name="description"
                        style={{ marginBottom: 0 ,width: '100%'}}
                    >
                        <Input.TextArea placeholder="请输入描述" rows={1} />
                    </Form.Item>
                ) : (formData.description || '-'),
            }
        ];
    },  [formData, is_edit, departmentOptionsMemo, access_type]); // 优化依赖项，使用 departmentList.length 而不是整个数组


    // 额外组件
    const extraComponents = () => {
        // 只有非编辑状态下才显示返回按钮
        if (is_edit) {
            return null;
        }
        return (
            <Flex gap={10} justify="end" align="center" style={{ width: '100%' }}>
                <AuthButton
                    permissions={['permission:update','permission:list']}
                >
                    <Button type="primary" onClick={handleEditClick}>
                        编辑
                    </Button>
                </AuthButton>
                {roleList.length > 0 && currentIndex >= 0 && (
                    <span style={{ marginLeft: 20, fontSize: 12, color: '#666' }}>
                        {currentIndex + 1} / {roleList.length}
                    </span>
                )}
                <AuthButton
                    permissions={['permission:list']}
                >
                    <Button 
                        type="default" 
                        onClick={navigateToPrevious}
                        disabled={currentIndex <= 0 || navigationLoading}
                        title={currentIndex <= 0 ? '已经是第一条' : `上一条: ${currentIndex > 0 ? roleList[currentIndex - 1]?.name : ''}`}
                    >
                        <LeftOutlined />
                    </Button>
                </AuthButton>
                <AuthButton
                    permissions={['permission:list']}
                >
                    <Button 
                        type="default" 
                        onClick={navigateToNext}
                        disabled={currentIndex >= roleList.length - 1 || navigationLoading}
                        title={currentIndex >= roleList.length - 1 ? '已经是最后一条' : `下一条: ${currentIndex < roleList.length - 1 ? roleList[currentIndex + 1]?.name : ''}`}
                    >
                        <RightOutlined />
                    </Button>
                </AuthButton>
                

            </Flex>
        )
    }


    // 提交表单
    const handleSubmit = async (values) => {
        // 获取权限数据
        const permissionData = functionPermissionRef?.current?.getData();
        
        // 获取数据权限
        const dataPermission= dataPermissionRef?.current?.getData();
        
        // 处理状态转换
        values.status = values.status ? 0 : 1;
        
        // 数据权限(默认全部)
        values.data_scope = 1;
        values.data_scope_dept_ids = [];
        
        // 如果有数据权限，则使用数据权限
        if(dataPermission){
            values.data_scope = dataPermission?.data_scope;
            values.data_scope_dept_ids = dataPermission?.data_scope_dept_ids;
        }
        // 汇总参数
        const params = {
            formdata: values,
            menus:[...checkedKeys],// 菜单
            permissions:[...permissionData],// 权限
        }

        // 新增
        if(access_type==='add'){
            // 提交数据
            const [err, ] = await adminApi.createRole(params);

            if(err){
                // message.error(err.message || '更新角色失败');
                return;
            }

            message.success('添加角色成功',3,()=>{    
                navigate('/setting/role',{replace:true})
            });

            

            return
        }        

                
        // 编辑提交数据
        const [err, ] = await adminApi.updateRole(params);

        if(err){
            message.error(err.message || '更新角色失败');
            return;
        }

        message.success('更新角色成功',3,()=>{
            navigate('/setting/role',{replace:true})
        });
       
    };


    

    return (
        <div className={styles.container}>
            <div className={styles.header}>
                {/* 角色详情区域 */}
                <Form
                    name="role_detail_form"
                    form={form}
                    initialValues={{}}
                    // colon={!is_edit}
                    autoComplete="off"
                    style={{ width: '100%' }}
                    onFinish={handleSubmit}
                >   
                    <Form.Item
                        hidden
                        name="id"
                    >
                        <Input disabled />
                    </Form.Item>
                    <Descriptions
                        className="header_form_descriptions"
                        title={
                            <Flex justify="start" align="center" style={{ width: '30%' }}>
                                <Link style={{ cursor: 'pointer' }} to={referrer}><LeftOutlined /> 返回</Link>
                                <h3 style={{ margin: 0 ,marginLeft: 10}}>角色详情</h3>
                            </Flex>
                        }
                        bordered={!is_edit}
                        column={{xs: 6, sm: 8, md: 12, lg: 24}}
                        size={'small'}
                        extra={extraComponents()}
                        items={cloumns || []}
                    />
                </Form>
            </div>
            <div className={styles.content}>
                {/* 权限区域 */}
                {/* <Spin spinning={loading}> */}
                <Tabs style={{ width: '100%', height:'100%'}} defaultActiveKey="1" items={Items}   />
                {/* </Spin> */}
            </div>
            <div className={styles.footer}>
                {/* 审计日志组件 */}
                {
                    is_edit ?
                        <Flex gap={10} justify="end" style={{ width: '100%' }}>
                            {access_type === 'add' ? null : <Button type="default" onClick={handleCancelClick}>
                                取消
                            </Button>}
                            <AuthButton
                                permissions={['permission:update','permission:list']}
                            >
                                <Button type="primary" htmlType="submit" onClick={handleSaveClick}>
                                    保存
                                </Button>
                            </AuthButton>
                        </Flex> :
                    <Audit data={formData} />
                }
            </div>
        </div>
    );
};
export default RoleDetail;
